package com.javastudy.liuhouse.xml_json;

import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;

/**
 * 使用Sax对xml文件进行解析
 */
public class SaxParse {

    @Test
    public void mains() throws ParserConfigurationException, SAXException, IOException {
        //加载文件并且以流的形式存在
        InputStream input = getClass().getClassLoader().getResourceAsStream("demo.xml");
        //创建一个SAXParserFactory 创建一个实例工厂 【这个是学习过的，大概知道】
        SAXParserFactory spf = SAXParserFactory.newInstance();
        //从SAXParserFactory实例工厂中  创建一个解析器对象
        SAXParser saxParser = spf.newSAXParser();
        //对输入的文件进行解析，然后使用对应的类来进行处理
        saxParser.parse(input , new MyHandler());
    }
}


class MyHandler extends DefaultHandler{
    @Override
    public void startDocument() throws SAXException {
        System.out.println("startDocument");
    }

    @Override
    public void endDocument() throws SAXException {
        System.out.println("endDocument");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.println("start element :" + localName + qName);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println("end element :" + localName + qName);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        System.out.println("characters:" + new String(ch , start , length));
    }

    @Override
    public void error(SAXParseException e) throws SAXException {
        System.out.println("error:" + e.getMessage());
    }
}
